import './public-path.js';
import './index.css';
import { handleRoute } from './router';

let app = null;

function render(props = {}) {
  const { container } = props;
  const dom = container ? container.querySelector('#app') : document.getElementById('app');
  
  dom.innerHTML = `
    <div class="native-app">
      <header class="app-header">
        <h1>原生JS子应用</h1>
        <p id="current-route">当前路由: /</p>
      </header>
      
      <nav class="app-nav">
        <a href="/" class="nav-link" data-path="/">首页</a>
        <a href="/page1" class="nav-link" data-path="/page1">Page 1</a>
        <a href="/page2" class="nav-link" data-path="/page2">Page 2</a>
      </nav>
      
      <div class="app-content" id="app-content">
        <div id="page-content"></div>
      </div>
    </div>
  `;
  
  // 添加路由处理逻辑
  updateContent(window.location.pathname);
  
  // 绑定导航事件
  const navLinks = dom.querySelectorAll('.nav-link');
  navLinks.forEach(link => {
    link.addEventListener('click', function(e) {
      e.preventDefault();
      const path = this.getAttribute('data-path');
      updateContent(path);
      
      // 更新当前路由显示
      document.getElementById('current-route').textContent = '当前路由: ' + path;
    });
  });
  
  // 监听主应用传来的路由变化事件
  window.addEventListener('main-app-route-change', function(event) {
    console.log('[native-app] received route change from main app:', event.detail);
    updateContent(event.detail);
  });
}

function updateContent(path) {
  const content = document.getElementById('page-content');
  content.innerHTML = handleRoute(path);
}

if (window.__POWERED_BY_QIANKUN__) {
  // eslint-disable-next-line no-undef
  __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
} else {
  render();
}

export async function bootstrap() {
  console.log('[native-app] native app bootstraped');
}

export async function mount(props) {
  console.log('[native-app] props from main framework', props);
  render(props);
}

export async function unmount() {
  if (app) {
    // 清理工作
    app = null;
  }
}